package com.qf.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.Objects;


public class MyBatisUtils {

    private static SqlSessionFactory factory;

    private static ThreadLocal<SqlSession> tl = new ThreadLocal<>();

    static {
        try {
            InputStream inputStream = Resources.getResourceAsStream("mybatis_config.xml");
            factory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SqlSession openSession() {
        SqlSession session = tl.get();
        if (Objects.isNull(session)) {
            session = factory.openSession();
            tl.set(session);
        }
        return session;
    }

    public static void closeSession() {
        SqlSession session = tl.get();
        session.close();
        tl.remove();
    }

    public static void commit() {
        SqlSession session = openSession();
        session.commit();
        closeSession();
    }

    public static void rollback() {
        SqlSession session = openSession();
        session.rollback();
        closeSession();
    }

    public static <T extends Object> T getMapper(Class<T> clazz) {
        SqlSession session = openSession();
        return session.getMapper(clazz);
    }

    public static SqlSession getSqlsession(){
        SqlSession sqlSession = null;
        try {
            InputStream is = Resources.getResourceAsStream("mybatis_config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            sqlSession = sqlSessionFactory.openSession(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sqlSession;
    }

}
